package com.yushu.common.util.collection;

import com.alibaba.fastjson.JSON;

import java.util.*;


 /**
 * Java集合工具类
 * @author test
 * @CreateDate 2020-12-03 15:47:24
 */
public class CollectionUtil {


    /**
     * 判断是否为空.
     */
    public static boolean isEmpty(Collection collection) {
        return ((collection == null) || collection.isEmpty());
    }

    /**
     * 判断是否为空.
     */
    public static boolean isNotEmpty(Collection collection) {
        return ((collection != null) && !(collection.isEmpty()));
    }


    /**
     * 返回a+b的新List.
     */
    public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
        List<T> result = new ArrayList<T>(a);
        result.addAll(b);
        return result;
    }


    /**
     * 查询自身集合中的交集
     */
    public static <T> List<T> intersection(List<List<T>> collections) {
        List<T> list = new ArrayList<T>();
        List<String> list2 = new ArrayList<String>();

        for (int i = 0; i < collections.size(); i++) {
            Collection<T> collections1 = collections.get(i);
            for (int j = 0; j < collections1.size(); j++) {
                T element = ((List<T>) collections1).get(j);
                String jsonObj = JSON.toJSONString(element);

                if (!list2.contains(jsonObj)) {
                    list2.add(jsonObj);
                }
            }

        }

        for (int i = 0; i < list2.size(); i++) {
            T element = (T) JSON.parse(list2.get(i));
            list.add(element);
        }
        return list;
    }

    public static <T> List<T> intersection(List<T> leftLists, List<T> rightLists) {
        List<T> listTarget = new ArrayList<T>();
        List<String> listCurrent = new ArrayList<String>();

        for (int i = 0; i < leftLists.size(); i++) {
            T leftData = leftLists.get(i);
            String leftJson = JSON.toJSONString(leftData);

            for (int j = 0; j < rightLists.size(); j++) {
                T rightData = rightLists.get(j);
                String rightJson = JSON.toJSONString(rightData);

//
                if (leftJson.equals(rightJson) && !listCurrent.contains(leftJson)) {
                    listCurrent.add(leftJson);
                }

            }

        }

        for (int i = 0; i < listCurrent.size(); i++) {
            T element = (T) JSON.parse(listCurrent.get(i));
            listTarget.add(element);
        }
        return listTarget;
    }
}
